package com.mzj.saas.mservice.code.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.code.entity.BusinessCode;
import com.mzj.saas.mservice.code.repository.BusinessCodeRepository;
import com.mzj.saas.mservice.code.vo.BusinessCodeVO;
import com.mzj.saas.mservice.sreach.entity.AppKeywordSreach;
import com.mzj.saas.mservice.sreach.repository.AppKeywordSreachRepository;
import com.mzj.saas.redis.RedisService;
import com.qiyuesuo.sdk.v2.utils.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class BusinessCodeService {
    private static final Logger log = LoggerFactory.getLogger(BusinessCodeService.class);
    @Autowired
    private RedisService redisService;
    @Autowired
    private BusinessCodeRepository businessCodeRepository;
    @Autowired
    private AppKeywordSreachRepository appKeywordSreachRepository;

    /**
     * 生成搜索记录与缴费记录
     *
     * @param accessToken
     * @param vo
     * @return
     * @author shun
     * @date 2021年6月24日
     */
    public ResultBean<Object> code(String accessToken, BusinessCodeVO vo) {
        log.info(" BusinessCodeService, accessToken={}, vo={}", accessToken, JSON.toJSONString(vo));
        ResultBean<Object> result = new ResultBean<>();
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }

            if (vo.getType() == null) {
                return ResultBean.failedResultWithMsg("类型为空");
            }

            if (vo.getType() == 1 && (StringUtils.isEmpty(vo.getContractNubmer()) || StringUtils.isEmpty(vo.getShortUrl()))) {
                return ResultBean.failedResultWithMsg("合同参数有误");
            }

            if (vo.getType() == 6 && vo.getRepairsId() == null) {
                return ResultBean.failedResultWithMsg("维修ID为空");
            }
            //类型 1合同 2公租房租金押金 3公租房其它缴费 4物业租金 5物业其它缴费 6维修
            if ((vo.getType() == 2 || vo.getType() == 3 || vo.getType() == 4 || vo.getType() == 5)
                    && (vo.getAmount() == null || CollectionUtils.isEmpty(vo.getHouseIds()))) {
                return ResultBean.failedResultWithMsg("账单参数有误");
            }

            //7生活缴费
            if (vo.getType() == 7 && (vo.getAmount() == null || CollectionUtils.isEmpty(vo.getHouseIds()) || vo.getHouseType() == null)
                    && ( CollectionUtils.isEmpty(vo.getOrderIds()) && CollectionUtils.isEmpty(vo.getExpenseIds())
                    && CollectionUtils.isEmpty(vo.getEstateRentIds()) && CollectionUtils.isEmpty(vo.getEstateExpenseIds()) )) {
                return ResultBean.failedResultWithMsg("账单参数有误");
            }


            String code = null;
            BusinessCode businessCode = null;
            if (vo.getType() == 1) {
                businessCode = new BusinessCode();
                code = vo.getContractNubmer();
                businessCode.setCode(code);
            } else if (vo.getType() == 2 || vo.getType() == 3 || vo.getType() == 4 || vo.getType() == 5 || vo.getType() == 6 || vo.getType() == 7) {
                if (StringUtils.isNotEmpty(vo.getContractNubmer()) && vo.getType() != null) {
                    businessCode = businessCodeRepository.findByContractNubmerAndType(vo.getContractNubmer(), vo.getType());
                }
                if (businessCode == null) {
                    businessCode = new BusinessCode();
                    code = getPayCodeNumber();
                    businessCode.setCode(code);
                }
            }

            // 生成关键字搜索记录
            AppKeywordSreach sreach = appKeywordSreachRepository.findByKeyword(businessCode.getCode());
            if (sreach == null) {
                sreach = new AppKeywordSreach();
            }
            sreach.setKeyword(businessCode.getCode());
            sreach.setPath(vo.getUrl());
            sreach.setCreateTime(new Date());
            appKeywordSreachRepository.save(sreach);

            // 保存记录
            businessCode.setContractNubmer(vo.getContractNubmer());
            businessCode.setParams(JSON.toJSONString(vo));
            businessCode.setType(vo.getType());
            businessCode.setOperatorId(tokenRedisVo.getId());
            businessCode.setCreateTime(new Date());
            businessCodeRepository.save(businessCode);

            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("code", businessCode.getCode());
            result.setResultData(resultMap);

            result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
            result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }

        return result;
    }

    public ResultBean<Object> getCodeInfo(String accessToken, String code, Integer flag, Integer type) {
        log.info(" BusinessCodeService, accessToken={}, code={}, flag={}, type={}", accessToken, code, flag, type);
        ResultBean<Object> result = new ResultBean<>();
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }

            // 保存记录
            BusinessCode entity = null;
            if (flag == null || flag == 1) {
                entity = businessCodeRepository.findByCode(code);
            } else if (flag != null && flag == 2 && type != null) {
                entity = businessCodeRepository.findByContractNubmerAndType(code, type);
            } else {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg("参数有误");
                return result;
            }

            BusinessCodeVO vo = null;
            if (entity != null) {
                vo = JSONObject.parseObject(entity.getParams(), BusinessCodeVO.class);
                if (vo != null) {
                    vo.setCode(entity.getCode());
                }
            }
            result.setResultData(vo);

            result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
            result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }

        return result;
    }

    /**
     * 生成缴费编码
     *
     * @return
     * @author shun
     * @date 2021年6月24日
     */
    public String getPayCodeNumber() {
        Long number = redisService.incr("BUSINESS_CODE", 24);
        int len = 20 - number.toString().length();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < len; i++) {
            builder.append("0");
        }
        return DateUtils.format(new Date(), DateUtils.FORMAT_8) + builder.toString() + number;
    }
}
